package ru.nsu.fit.iconveyor.conveyor.storage.importer.graphml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import ru.nsu.fit.iconveyor.conveyor.Conveyor;
import ru.nsu.fit.iconveyor.conveyor.storage.importer.IDecoder;
import ru.nsu.fit.iconveyor.conveyor.node.Node;

/**
 * @author Timur Zolotuhin (tzolotuhin@gmail.com)
 */
public class GraphMLDecoder implements IDecoder {
		@Override
    public Conveyor decode(String fileName, Map<String, Class<Node>> classes, Properties prop) throws Exception {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            GraphMLParser handler = new GraphMLParser(classes);
            FileInputStream fis = new FileInputStream(fileName);

            saxParser.parse(fis, handler);
            Conveyor conv = handler.getConveyor();
            return conv;
        } catch (ParserConfigurationException e) {
            throw e;
        } catch (SAXParseException e) {
            throw new Exception(fileName + ":" + e.getLineNumber() + ":" + e.getColumnNumber() + " " + e.getMessage());
        } catch (SAXException e) {
            throw e;
        } catch (FileNotFoundException e) {
            throw new Exception("File " + fileName + " don't found");
        } catch (IOException e) {
            throw e;
        }
    }
}
